package com.zl.iot.docking.service;

import com.zl.iot.docking.config.ServerInfo;
import com.zl.iot.docking.exception.MyExceptionNew;
import com.zl.iot.docking.exception.ZLExcep;
import com.zl.iot.docking.model.AliServerVO;
import org.slf4j.Logger;

import javax.jms.*;

/**
 * @author chenzy
 * @since 2021-11-02
 * 订阅者-消费
 **/
public abstract class Consumer {
    public static final Logger logger = ServerInfo.getInfoLog();
    public final Connection connection;
    public final AliServerVO aliServer;

    public Consumer(AliServerVO aliServer, Connection connection, Destination queue) {
        logger.info("开始创建实例");
        this.aliServer = aliServer;
        this.connection = connection;
        /*创建会话 Session.CLIENT_ACKNOWLEDGE: 收到消息后，需要手动调用message.acknowledge()
            Session.AUTO_ACKNOWLEDGE: SDK自动ACK（推荐）
            */
        try {
            var session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            connection.start();
            // 创建Receiver连接。
            session.createConsumer(queue).setMessageListener(this::consumer);
        } catch (JMSException e) {
            e.printStackTrace();
            throw ZLExcep.error("创建消费者失败", e);
        }
        logger.info("创建实例成功");
    }
    public abstract void consumer(Message message);
 /*   private void setHead(String key, String value) {
        var head = BaggageField.getByName(key);
        if (head == null) {
            head = BaggageField.create(key);
        }
        head.updateValue(value);
    }*/

    public void close() {
        try {
            connection.close();
        } catch (JMSException e) {
            throw ZLExcep.error("关闭阿里云订阅消息的连接失败", e);
        }
    }
}
